import 'package:logger/logger.dart';

/// 性能监控工具类
class PerformanceMonitor {
  static final Logger _logger = Logger();
  static final Map<String, DateTime> _startTimes = {};

  /// 开始计时
  static void startTimer(String name) {
    _startTimes[name] = DateTime.now();
    _logger.i('⏱️ 开始计时: $name');
  }

  /// 结束计时并输出结果
  static void endTimer(String name) {
    final startTime = _startTimes[name];
    if (startTime == null) {
      _logger.w('⚠️ 未找到计时器: $name');
      return;
    }

    final endTime = DateTime.now();
    final duration = endTime.difference(startTime);
    _logger.i('⏱️ 计时结束: $name - 耗时: ${duration.inMilliseconds}ms');
    
    _startTimes.remove(name);
  }

  /// 测量异步操作的执行时间
  static Future<T> measureAsync<T>(
    String name,
    Future<T> Function() operation,
  ) async {
    startTimer(name);
    try {
      final result = await operation();
      endTimer(name);
      return result;
    } catch (e) {
      endTimer(name);
      rethrow;
    }
  }

  /// 测量同步操作的执行时间
  static T measureSync<T>(
    String name,
    T Function() operation,
  ) {
    startTimer(name);
    try {
      final result = operation();
      endTimer(name);
      return result;
    } catch (e) {
      endTimer(name);
      rethrow;
    }
  }
}